package com.thghh.executor;

import lombok.Getter;
import org.springframework.stereotype.Component;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.Callable;
import java.util.concurrent.Future;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 包名称：com.thghh.executor
 * 类名称：TaskPoolScheduler
 * 类描述：任务调度
 * 创建人：@author pengzhikang
 * 创建时间：2021/9/3 9:37
 */
@Component
public class TaskPoolScheduler {

    private int poolSize;

    private TaskPoolExecutor taskPoolExecutor;

    @Getter
    private BlockingQueue<Runnable> blockingQueue;

    public TaskPoolScheduler() {
        blockingQueue = new LinkedBlockingQueue<>(1000);
        poolSize = 32;

        initPoolExecutor();
    }

    /**
     * 获取同时完成任务的服务提供者
     *
     * @param taskCount 任务数量
     * @return MeantimeCompletionService
     * @author pengzhikang
     * @date 2021/9/3 11:32
     */
    public MeantimeCompletionService getMeantimeCompletionService(int taskCount) {
        return new MeantimeCompletionService(taskCount, taskPoolExecutor);
    }

    /**
     * 初始化线程池，初始大小为系统可用处理器大小
     *
     * @author pengzhikang
     * @date 2021/9/3 10:07
     */
    private void initPoolExecutor() {
        taskPoolExecutor = new TaskPoolExecutor(poolSize, poolSize, 0L, TimeUnit.MILLISECONDS, blockingQueue);
    }

    /**
     * 提交任务
     *
     * @param task 任务
     * @return Future<T> 返回值
     * @author pengzhikang
     * @date 2021/9/3 10:43
     */
    public <T> Future<T> submit(Task<T> task) {
        return taskPoolExecutor.submit(task::task);
    }

    /**
     * 提交任务
     *
     * @param task 任务
     * @return Future<T> 返回值
     * @author pengzhikang
     * @date 2021/9/3 10:43
     */
    public <T> Future<T> submit(Callable<T> task) {
        return taskPoolExecutor.submit(task);
    }

    /**
     * 提交任务
     *
     * @param task 任务
     * @return Future<T> 返回值
     * @author pengzhikang
     * @date 2021/9/3 10:43
     */
    public Future<?> submit(Runnable task) {
        return taskPoolExecutor.submit(task);
    }

    /**
     * 提交任务
     *
     * @param task   任务
     * @param result 返回结果
     * @return Future<T> 返回值
     * @author pengzhikang
     * @date 2021/9/3 13:16
     */
    public <T> Future<T> submit(Runnable task, T result) {
        return taskPoolExecutor.submit(task, result);
    }
}
